package com.qk.interceptor;

import com.qk.common.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求路径
        String uri = request.getRequestURI();// /users (获取的就是后面这一部分 不包括前面的localhost:90....)

        //2.判断是否是登录请求
        if (uri.contains("login")) {
            log.info("登录请求:{}", uri);
            return true;
        }
        //3.获取请求头token,
        String jwt = request.getHeader("token");

        //4.判断是否有token,不存在响应401
        if (jwt == null || jwt.isEmpty()) {
            log.info("请求头没有token");
            response.setStatus(401);
            return false;
        }
        //5.解析token,判断是否合法,不合法响应401
        try {
            Claims claims = JwtUtils.parseToken(jwt);
            log.info("解析成功:{}", claims);
        } catch (Exception e) {
            log.info("解析token异常:{}", e.getMessage());
            response.setStatus(401);
            return false;
        }
        //6.放行
        return true;
    }
}
